package com.liuhuan.alipaydemo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.liuhuan.alipaydemo.config.AliPayConfig;
import com.liuhuan.alipaydemo.pojo.AliPayBean;
import com.liuhuan.alipaydemo.service.PayModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AliPayController {
    private final String CHARSET = "UTF-8";
    @Autowired
    private PayModelService model;

    @GetMapping(value = "/alipay")
    public String alipay() throws AlipayApiException, IOException {
        String subject="林肯加长版";
        String  outTradeNo="26519498919132";
        String  totalAmount="256.0";
        AliPayBean alipayBean = new AliPayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject("正在支付购买 《"+subject+"》 的订单");
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody("欢迎支付林肯官网商品");
        return model.aliPay(alipayBean);
    }
    @RequestMapping("/returnUrl")
    @ResponseBody
    public String returnUrlMethod(HttpServletRequest request, HttpSession session, Model model) throws AlipayApiException, UnsupportedEncodingException
    {
        System.out.println("= 同步回调 =====");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            //  valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        AliPayConfig aliPayConfig=new AliPayConfig();
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getPublicKey(), CHARSET, aliPayConfig.getSignType()); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易流水号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+money);

            //在这里编写自己的业务代码（对数据库的操作）
		/*
		################################
		*/
            //跳转到提示页面（成功或者失败的提示页面）
            // model.addAttribute("flag",1);
            // model.addAttribute("msg","支持");
            return  out_trade_no+":"+trade_no+":"+money;
        }else{
            //跳转到提示页面（成功或者失败的提示页面）
            // model.addAttribute("flag",0);
            // model.addAttribute("msg","支持");
            return "回调失败 支付失败";
        }
    }
}
